package com.wemedia.gateway.filter;

import com.usian.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * ClassName: AuthorizeFilter@Component
 * Author:   WGG
 * Date:    2022-11-2022/11/11-19:31
 * Version: 1.0
 * Description:
 */

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取 request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //指定可放行路径
        if (request.getURI().getPath().contains("/login/in")){
            return chain.filter(exchange);
        }
        try {
            //判断 token 是否存在
            //获取当前用户请求头jwt信息
            HttpHeaders headers = request.getHeaders();
            String token = headers.getFirst("token");
            if (StringUtils.isEmpty(token)){
                //如果用户不存在，返回
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //解析token中的内容
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //校验
            int i = AppJwtUtil.verifyToken(claims);
            //说明token是否在有效期
            if (i==-1||i==0){
                //合法，则向header中重新设置userId
                Integer id = (Integer)claims.get("id");
                log.info("=======================userid:{} =============================uri:{}",id,request.getURI());
                //重新设置token到header中
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("userId",id+"");
                }).build();
                exchange.mutate().request(serverHttpRequest).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //向客户端返回信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 放行
        return chain.filter(exchange);
    }

    /**
     * 优先级介绍
     * 值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
